export default function (method, url, params = {}) {
    return new Promise(function (resolve, reject) {


        const xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    resolve(JSON.parse(xhr.response))
                } else {
                    if (xhr.status == 401) {
                        alert('未登录或登陆超时\n请重新登录');
                        location = '/login.html?url=' + encodeURIComponent(location.href)
                    } else {
                        alert('服务器错误')
                        reject(xhr.status);
                    }
                }
            }
        }


        const data = Object.entries(params).map(item => item[0] + '=' + encodeURIComponent(item[1])).join('&');
        //当请求类型为get时，我们将参数变为字符串拼接到url后面
        if (method.toLowerCase() == 'get') {
            url += '?' + data;
        }

        xhr.open(method, url, true);

        if (method.toLowerCase() == 'post') {
            // xhr.setRequestHeader('Content-Type', 'Application/x-www-form-urlencoded');
            xhr.setRequestHeader('Content-Type', 'application/json');
        }

        //读取token，添加token到请求头中
        xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));

        xhr.send(method.toLowerCase() == 'get' ? null : JSON.stringify(params));
    })
}